package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.ISpcySqsxBaiscService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.service.ISpcySqsxWjmlService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 审评查验-文件目录
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
@Api(tags = "审评查验-文件目录库接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcySqsxWjml")
public class SpcySqsxWjmlController extends BaseController<SpcySqsxWjml, ISpcySqsxWjmlService> {

    private static final Logger log = LoggerFactory.getLogger(SpcySqsxWjmlController.class);

    @Resource
    private ISpcySqsxWjmlService spcySqsxWjmlService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    /**
     * 分页列表查询
     *
     * @param spcySqsxWjml
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Log(title = "文件目录-分页列表查询")
    @ApiOperation(value = "文件目录-分页列表查询")
    @GetMapping(value = "/queryWjmlPageList")
    public HttpResult<?> queryWjmlPageList(SpcySqsxWjml spcySqsxWjml, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SpcySqsxWjml> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SpcySqsxWjml> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(spcySqsxWjml.getFywflcode()),SpcySqsxWjml::getFywflcode,spcySqsxWjml.getFywflcode());
        queryWrapper.like(StringUtils.isNotEmpty(spcySqsxWjml.getFwjlx1()),SpcySqsxWjml::getFwjlx1,spcySqsxWjml.getFwjlx1());
        queryWrapper.like(StringUtils.isNotEmpty(spcySqsxWjml.getFwjlx2()),SpcySqsxWjml::getFwjlx2,spcySqsxWjml.getFwjlx2());
        queryWrapper.like(StringUtils.isNotEmpty(spcySqsxWjml.getFwjlx3()),SpcySqsxWjml::getFwjlx3,spcySqsxWjml.getFwjlx3());
        queryWrapper.like(StringUtils.isNotEmpty(spcySqsxWjml.getFlxmc()),SpcySqsxWjml::getFlxmc,spcySqsxWjml.getFlxmc());
        queryWrapper.orderByAsc(SpcySqsxWjml::getFwjlx1);
        queryWrapper.orderByAsc(SpcySqsxWjml::getForder);
        queryWrapper.orderByAsc(SpcySqsxWjml::getCreateTime);
        IPage<SpcySqsxWjml> pageList = spcySqsxWjmlService.page(page, queryWrapper);
        return HttpResult.ok(pageList);
    }

    @Log(title = "获取现场检查材料-文件目录类型")
    @ApiOperation(value = "获取现场检查材料-文件目录类型")
    @ApiImplicitParam(name = "fywflcode",value = "业务分类编码",required = true)
    @GetMapping(value = "queryWjmlTypeList")
    public HttpResult<?> queryWjmlTypeList(@RequestParam("fywflcode")String fywflcode){
        if (StringUtils.isBlank(fywflcode)){
            return HttpResult.error("业务分类编码不能为空");
        }
        LambdaQueryWrapper<SpcySqsxWjml> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxWjml::getFywflcode,fywflcode);
        queryWrapper.orderByAsc(SpcySqsxWjml::getForder);
        queryWrapper.orderByAsc(SpcySqsxWjml::getCreateTime);
        List<SpcySqsxWjml> wjmlList = spcySqsxWjmlService.list(queryWrapper);
        List<String> wjlxList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(wjmlList)) {
            wjlxList = wjmlList.stream().map(SpcySqsxWjml::getFlxmc).collect(Collectors.toList());
        }
        Map resultMap = new HashMap();
        resultMap.put("wjlxList", wjlxList);

        return HttpResult.ok(resultMap);
    }


    /**
     * 添加
     *
     * @param spcySqsxWjml
     * @return
     */
    @Log(title = "文件目录-添加")
    @ApiOperation(value = "文件目录-添加")
    @PostMapping(value = "/addWjml")
    public HttpResult<?> addWjml(@RequestBody SpcySqsxWjml spcySqsxWjml) {
        String operContent = "新增信息：";

        spcySqsxWjml.setId(GetUuIdUtils.ReplaceUuId());
        spcySqsxWjmlService.save(spcySqsxWjml);
        // 将map里面的属性和值转String
        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(spcySqsxWjml);
        operContent += LogUtils.MapToStringMethod(beanMap);
        spcyLogService.addLogs(LogConstant.LOGS_SQSX_WJML,operContent,spcySqsxWjml.getId(), LogConstant.LOGS_SQSX_WJML, SpcyConstant.LOGS_SYS_TYPE_XZ);
        return HttpResult.ok("添加成功");
    }

    /**
     * 编辑
     *
     * @return
     */
    @Log(title = "文件目录-编辑")
    @ApiOperation(value = "件目录-编辑")
    @ApiImplicitParam(name = "id",value = "文件目录id",required = true)
    @PutMapping(value = "/editWjml")
    public HttpResult<?> edit(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException {
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("文件目录信息id不能为空");
        }
        String wjmlId = buffer.get("id");
        SpcySqsxWjml oldWjml = spcySqsxWjmlService.getById(wjmlId);
        SpcySqsxWjml oldWjmlUpdate = spcySqsxWjmlService.getById(wjmlId);
        if (oldWjmlUpdate == null){
            return HttpResult.error("当前文件目录基本信息数据不存在，请重试");
        }
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(oldWjmlUpdate, buffer);
        spcySqsxWjmlService.updateById(oldWjmlUpdate);

        String operContent = "基本信息修改：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldWjml);
        operContent += LogUtils.BeanModifyMsg(oldWjmlUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_SQSX_WJML,operContent,wjmlId,LogConstant.LOGS_SQSX_WJML,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return
     */
    @Log(title = "文件目录-批量删除")
    @ApiOperation(value = "文件目录-批量删除")
    @DeleteMapping(value = "/deleteBatchWjml")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SpcySqsxWjml> sqsxWjmlList = spcySqsxWjmlService.listByIds(idsList);
        if (CollectionUtils.isEmpty(sqsxWjmlList)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SpcySqsxWjml wjml : sqsxWjmlList){
            String id = wjml.getId();
            spcySqsxWjmlService.removeById(id);

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(wjml);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_SQSX_WJML,operContent,id,LogConstant.LOGS_SQSX_WJML,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Log(title = "文件目录-通过id查询")
    @ApiOperation(value = "文件目录-通过id查询")
    @GetMapping(value = "/queryWjmlById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SpcySqsxWjml spcySqsxWjml = spcySqsxWjmlService.getById(id);
        return HttpResult.ok(spcySqsxWjml);
    }

    /**
     * 导入文件目录数据-表格excel
     */
    @Log(title = "导入文件目录数据-表格excel")
    @ApiOperation(value = "导入文件目录数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true),
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码",required = true)
    })
    @PostMapping(value = "impSqsxWjmlData")
    public HttpResult<?> impRsGcyData(@RequestParam("file") MultipartFile file, @RequestParam("fywflcode")String ywflCode){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isEmpty(ywflCode)){
            return HttpResult.error("业务分类编码不能为空");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_SQSX_WJML_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入文件目录数据出错-{}",e.getMessage());
        }
        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (Map map : mapsList) {
                SpcySqsxWjml spcySqsxWjml = new SpcySqsxWjml();
                BeanUtil.copyProperties(map,spcySqsxWjml);
                String wjmlId = GetUuIdUtils.NotReplaceUuId();
                spcySqsxWjml.setId(wjmlId);
                spcySqsxWjml.setFywflcode(ywflCode);
                spcySqsxWjmlService.save(spcySqsxWjml);

                String operContent = "新增导入信息：";

                // 将map里面的属性和值转String
                Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(spcySqsxWjml);
                operContent += LogUtils.MapToStringMethod(beanMap);
                spcyLogService.addLogs(LogConstant.LOGS_SQSX_WJML,operContent,wjmlId, LogConstant.LOGS_SQSX_WJML,SpcyConstant.LOGS_SYS_TYPE_XZ);

            }
        }
        fileUpload.delete();
        return HttpResult.ok("导入成功");
    }

    /**
     * 下载文件目录-导入模板
     * @param response
     */
    @Log(title = "下载文件目录-导入模板")
    @ApiOperation(value = "下载文件目录-导入模板")
    @GetMapping("/downSqsxWjmlTemplate")
    public void downSqsxWjmlTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("wjmlImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_SQSX_WJML_XML, out);
        } catch (Exception e) {
            log.error("下载文件目录模板错误-{}",e.getMessage());
        }
    }

    /**
     * 导出文件目录数据-表格excel
     */
    @Log(title = "导出文件目录数据-表格excel")
    @ApiOperation(value = "导出文件目录数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "文件目录id字符逗号分割",dataType = "String")
    })
    @GetMapping("/exportSqsxWjmlData")
    public void exportSqsxWjmlData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                SpcySqsxWjml sqsxWjml,
                                HttpServletResponse response){
        try {
            String name = "exportSqsxWjml";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SpcySqsxWjml> rsGcyList = spcySqsxWjmlService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(rsGcyList)){
                    for (SpcySqsxWjml e : rsGcyList){
                        list.add(e);
                    }
                }
            }else {
                LambdaQueryWrapper<SpcySqsxWjml> queryWrapper = new LambdaQueryWrapper();
                queryWrapper.eq(StringUtils.isNotEmpty(sqsxWjml.getFywflcode()),SpcySqsxWjml::getFywflcode,sqsxWjml.getFywflcode());
                queryWrapper.like(StringUtils.isNotEmpty(sqsxWjml.getFwjlx1()),SpcySqsxWjml::getFwjlx1,sqsxWjml.getFwjlx1());
                queryWrapper.like(StringUtils.isNotEmpty(sqsxWjml.getFwjlx2()),SpcySqsxWjml::getFwjlx2,sqsxWjml.getFwjlx2());
                queryWrapper.like(StringUtils.isNotEmpty(sqsxWjml.getFwjlx3()),SpcySqsxWjml::getFwjlx3,sqsxWjml.getFwjlx3());
                queryWrapper.like(StringUtils.isNotEmpty(sqsxWjml.getFlxmc()),SpcySqsxWjml::getFlxmc,sqsxWjml.getFlxmc());
                queryWrapper.orderByAsc(SpcySqsxWjml::getForder);
                List<SpcySqsxWjml> wjmlList = spcySqsxWjmlService.list(queryWrapper);
                // 条件导出
                if (CollectionUtils.isNotEmpty(wjmlList)){
                    for (SpcySqsxWjml e : wjmlList){
                        list.add(e);
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_SQSX_WJML_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出文件目录数据出错-{}",e.getMessage());
        }
    }

    /**
     * 获取业务类型的文件目录-通过申请事项id
     */
//    @Log(title = "获取业务类型的文件目录-通过申请事项id")
//    @ApiOperation(value = "获取业务类型的文件目录-通过申请事项id")
//    @ApiImplicitParam(value = "sqsxId",name = "申请事项id",required = true)
//    @GetMapping(value = "getSqsxWjmlByYwfl")
    public HttpResult<?> getRsJbsxByYwfl(@RequestParam("sqsxId")String sqsxId){

        if (StringUtils.isEmpty(sqsxId)){
            return HttpResult.error("申请事项id参数不能为空");
        }
        SpcySqsxBasic sqsxBasic = spcySqsxBaiscService.selectSqsxById(sqsxId);
        if (sqsxBasic == null){
            return HttpResult.error("申请事项信息为空，请重试");
        }
        String ywflCode = "";
        if (StringUtils.isNotEmpty(sqsxBasic.getFywflcode())){
            ywflCode = sqsxBasic.getFywflcode();
        }
        List<SpcySqsxWjml> rsJbxxList = spcySqsxWjmlService.list(new LambdaQueryWrapper<SpcySqsxWjml>()
                .eq(SpcySqsxWjml::getFywflcode, ywflCode).orderByAsc(SpcySqsxWjml::getForder));
        return HttpResult.ok(rsJbxxList);
    }

}
